package com.example.administrator.fagementwc;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder> {
    private List<Contact> mContactList;
    private OnItemClickLitener mOnItemClickLitener;

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView contactImage;
        TextView contactName;
        View contactItem;

        public ViewHolder(View view) {//view表示contact_item的布局
            super(view);
            contactItem = view;
            //获取布局里的组件
            contactImage = (ImageView) itemView.findViewById(R.id.contactImage);
            contactName = (TextView) itemView.findViewById(R.id.contactName);

        }
    }

    public ContactAdapter(List<Contact> contactList) {
        mContactList = contactList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //加载contact_item成view
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.contact_item, parent, false);

        final ViewHolder holder = new ViewHolder(view);

        holder.contactItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();

                Contact contact = mContactList.get(position);
                int imagId = contact.getImageId();
                String name = contact.getName();
                mOnItemClickLitener.onItemClick(imagId, name);
//                Toast.makeText(v.getContext(), "you clicked view" + contact.getName(), Toast.LENGTH_SHORT).show();
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        //RecyclerView子项赋值
        Contact contact = mContactList.get(position);
        holder.contactImage.setImageResource(contact.getImageId());
        holder.contactName.setText(contact.getName());
    }

    @Override
    public int getItemCount() {
        //RecyclerView里有多少个子项
        return mContactList.size();
    }

    public interface OnItemClickLitener {
        public void onItemClick(int imageId, String name);
    }

    public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
        this.mOnItemClickLitener = mOnItemClickLitener;
    }


}
